import { Component, OnInit } from '@angular/core';
import { BladeContainerInterface } from "../../../../shared/blade/blade-container.interface";
import { Blade } from "../../../../shared/blade/blade.model";
import { Observable } from "rxjs/Observable";
import { FormBuilder, FormGroup, Validators, FormControl } from "@angular/forms";
import { SimpleChanges } from "@angular/core/core";
import { Command } from "../../../../shared/toolbar.service";
import { BladeContainerBase } from "../../../../shared/blade/blade-container-base";
import { BladeData } from "../../../../shared/blade/blade-data";
import { MyValidators } from "../../../../utils/validator/rang";
import { ColorChoicesComponent } from "../../../../shared/color-choices/color-choices.component";
import { MatrixStateGroup } from "../../../../entity/matrix-state-group.model";

import { MatrixState } from "../../../../entity/matrix_state.model";
import { MatrixStateService } from "../../../../service/matrix-state.service";


@Component({
	selector: 'app-matrix-state-edit',
	templateUrl: './matrix-state-edit.component.html',
	styleUrls: ['./matrix-state-edit.component.css']
})
export class MatrixStateEditComponent extends BladeContainerBase<MatrixState> {
	
	colorOut: {};
	constructor(
		private fb: FormBuilder,
		private matrixStateService: MatrixStateService,
	) { super(fb) }

	ngOnInit() {
		//编辑时注册按钮和按钮命令    
		if (!this.isNew) {
			this.commands = [
				new Command("save", "保存", "fa fa-save", "setofkey:update", (blade) => this.exeSaveChange(blade), (blade) => this.canSaveChange(blade)),
				new Command("reset", "重置", "fa fa-save", "setofkey:reset", (blade) => this.exeReset(blade), (blade) => this.canReset(blade)),
			]
		}
		else {
			this.currentEntity = new MatrixState(0, 0, '', true)
		}
		super.ngOnInit();
	}
	/**
     * 初始化数据
     * 
     * 
     * @memberof TurbstatusValueListComponent
     */
    initData(): any | Observable<any> | Promise<any> {
		if (this.parentBlade.parentEntity != null) {
			this.currentEntity.stateGroupId = (this.parentBlade.parentEntity as MatrixStateGroup).stateGroupId;
		}
        this.formPatchValue(this.currentEntity);
    }

	exeSaveChange(blade: any): void {
		this.saveChange();
	}
	canSaveChange(blade: any): boolean {
		return this.hasChange() && !this.hasError();
	}
	exeReset(blade: any): void {
		return this.formGroup.reset(this.currentEntity);
	}
	canReset(blade: any): boolean {
		return this.hasChange();
	}

	/**
	  * 创建表单
	  * 
	  * 
	  * @memberof DicKeyEditComponent
	  */
	createForm() {
		this.formGroup = this.fromBuider.group({
			"stateName": [this.currentEntity.stateName, [
				Validators.required,
				Validators.pattern("^[\u4e00-\u9fa5a-zA-Z0-9]+$"),
				Validators.maxLength(50),
			], (control: FormControl): any => this.stateNameAsnyValidator(control, this.currentEntity.stateName)
			],
			"stateColor": [this.currentEntity.stateColor, [
				Validators.required,
				Validators.pattern("^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$"),
				Validators.maxLength(7)
			],(control: FormControl): any => this.stateColorAsnyValidator(control)],//异步验证颜色；
			"stateColor2":[this.currentEntity.stateColor], 
			"remark": [this.currentEntity.remark, [		
				// MyValidators.rang(0, 255)
			],
			],
			"stateSeq": [this.currentEntity.stateSeq, [
				Validators.required,
				MyValidators.rang(0, 255)
			],
			],
			"unAlarm":[this.currentEntity.unAlarm],
			"unChecked":[this.currentEntity.unChecked],			
		});

		//插件的颜色选择
		this.formGroup.controls["stateColor2"].valueChanges.subscribe(form => {
		  if (this.formGroup.controls["stateColor"].value != form) {
		    this.formGroup.controls["stateColor"].setValue(form)
		  }

		})
		this.formGroup.controls["stateColor"].valueChanges.subscribe(form => {
		  if (this.formGroup.controls["stateColor2"].value != form) {
		    this.formGroup.controls["stateColor2"].setValue(form)
		  }
		})

	}
	/**
	* 设置表单错误对象
	* 
	* 
	* @memberof BladeContainerBase
	*/
	setFormError(): void {
		this.formErrors = {
			'stateName': '',
			'stateColor': '',
			'remark': '',
			'stateSeq': '',
		};
	}
	/**
	* 设置表单验证信息
	* 
	* 
	* @memberof BladeContainerBase
	*/
	setValidationMessages(): void {
		this.validationMessages = {
			'stateName': {
				'required': '状态名称不能为空。',
				'pattern': '状态名称必须是汉字字母数字。',
				'maxlength': '状态名称不能多于50个字符长度。',
				'exist': '状态名称已存在。',
			},
			'stateColor': {
				'required': '颜色值不能为空。',
				'pattern': '颜色值只能是以#开头的数字字母。',
				'maxlength': '颜色值只能是7个字符长度。',
				'exist': '颜色值已存在。',
			},
			'remark': {
				// 'required': '优先级值不能为空。',
				// 'rang': '优先值范围是0~255。',
				// 'exist': '优先级值已存在。',
			},
			'stateSeq': {
				'required': '排序值不能为空。',
				'rang': '排序值范围是0~255。',
			}
		};
	}

	/**
	 * 异步校验state名称是否存在
	 * 
	 * @param {FormControl} control 
	 * @returns {Promise<true>} 
	 * 
	 * @memberof turbstatusEditComponent
	 */
	stateNameAsnyValidator(control: FormControl, current: any): any {
		if (!control.value || control.value == current) {
			return Observable.of(null);
		}
		return this.matrixStateService.hasStateName(control.value, this.currentEntity.stateGroupId, this.currentEntity.stateId)  
			.map(res => res ? { exist: true } : null);
	}
	/**
	 * 异步校验statusColor是否存在
	 * 
	 * @param {FormControl} control 
	 * @returns {Promise<true>} 
	 * 
	 * @memberof turbstatusEditComponent
	 */
	stateColorAsnyValidator(control: FormControl): any {
		if (control.value == this.currentEntity.stateColor) {
			return Observable.of(null);
		}
		return this.matrixStateService.hasStateColor(control.value, this.currentEntity.stateId, this.currentEntity.stateGroupId)
			.map(res => res ? { exist: true } : null);
	}
	/**
	 * 创建一个风机状态
	 * 
	 * 
	 * @memberof TurbstatusEditComponent
	 */
	onCreate() {
		if (!this.hasError()) {
			this.changeCurrent();		
			this.matrixStateService.create(this.currentEntity)
				.then(res => {
					if (res.stateId) {
						let parentContainerInstance = this.parentBlade.bladeContainerInstance;
						parentContainerInstance.refresh(res);
						this.bladeService.closeBlade(this.currentBlade);
					}
				})
				.catch(error => this.bladeData.error = error)
				.then(res => this.bladeData.isLoading = false);
		}
	}
	/**
	 * 
	 * 
	 * 
	 * @memberof TurbstatusEditComponent
	 */
	saveChange(): any | Promise<any> | Observable<any> {
		if (this.canSaveChange(this.currentBlade)) {
			this.changeCurrent();
			return this.matrixStateService.update(this.currentEntity)
				.then(res => {
					if (res) {
						(this.parentBlade.bladeContainerInstance).refresh(res);
						this.bladeService.closeBlade(this.currentBlade);
						return true;
					}
				})
				.catch(error => this.bladeData.error = error)
				.then(res => this.bladeData.isLoading = false);
		}
	}
	changeCurrent() {
		this.bladeData.isLoading = true;
		let formValue = this.formGroup.value as MatrixState;
		this.currentEntity.stateName = formValue.stateName;
		this.currentEntity.stateColor = formValue.stateColor;
		this.currentEntity.remark = formValue.remark;
		this.currentEntity.stateSeq = formValue.stateSeq;
		this.currentEntity.unAlarm = formValue.unAlarm;
		this.currentEntity.unChecked = formValue.unChecked;
	}
	recPro(event: {}) {
		this.colorOut = event;
	}

}



// WEBPACK FOOTER //
// ./src/app/module/basic/matrix-config/matrix-state-edit/matrix-state-edit.component.ts